package gen.tools.query;

import gen.tools.Widgets;
import gen.tools.structures.S4;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryVincent extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryVincent() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding(wid.UIcodeSet);
		response.setContentType("application/json");
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ResultSet rs2 = null;
		
		final ArrayList<S4> s4s = new ArrayList<S4>();
		
		try {
			conn = wid.getConn();
			
			//查詢 某年 某月 的交付次數
			String sql = "SELECT DISTINCT YEAR(createdDateTime) as Y,MONTH(createdDateTime) as M FROM deltask t1,deplmain t2 WHERE t1.deplmainSN=t2.deplmainSN ORDER BY Y DESC, M DESC";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			
			while ( rs.next() ) {
				final S4 s4 = new S4();
				final int year = rs.getInt("Y");
				final int month = rs.getInt("M");
				//
				sql = "SELECT COUNT(*) FROM depmain WHERE YEAR(createdDateTime)=? AND MONTH(createdDateTime)=?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, year);
				ps.setInt(2, month);
				rs2 = ps.executeQuery();
				rs2.next();
				
				s4.setS1( String.valueOf( year ) );
				s4.setS2( String.valueOf( month ) );
				
				s4.setS4( String.valueOf( rs2.getInt(1) ) );
				
				sql = "SELECT COUNT(*) FROM deltask t1,deplmain t2 WHERE t1.deplmainSN=t2.deplmainSN AND YEAR(t2.createdDateTime)=? AND MONTH(t2.createdDateTime)=?";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, year);
				ps.setInt(2, month);
				rs2 = ps.executeQuery();
				rs2.next();
				s4.setS3( String.valueOf( rs2.getInt(1) ) );
				s4s.add(s4);
			}
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( rs2 !=null ) {rs2.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (SQLException e) {e.printStackTrace();}
		}

		response.getWriter().write( new Gson().toJson( s4s ) );
	}

}
